//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////

using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

#if Gdmp || Gnuf
using Glodon.Gdmp.DB;
#elif Gap
using Glodon.Gap.DB;
using Glodon.Gap.UI;
#endif
using Glodon.Lookup.Core.Contracts;
using Glodon.Lookup.Core.ModelBase;
using Glodon.Lookup.Lookup.Core;
using Glodon.Lookup.Utils;
using Glodon.Lookup.Views.Extensions;

namespace Glodon.Lookup.Models.Descriptors
{
    public class ElementDescriptor : Descriptor, IDescriptorResolver, IDescriptorConnector
    {
        private readonly string _unKnownCategory = "Unknow Category";
        private readonly string _categoryError = "Get Category Error";
        private readonly string _NameError = "Name Error";

        public bool CanShow { get; set; }

        private readonly Element _element;
        public ElementDescriptor(Element element)
        {
            try
            {
                _element = element;
                CanShow = GlodonAPI.GetBody(_element)?.Volume > 0;

                var categoryName = GetCategoryText(element);
                if (categoryName.Equals(_categoryError))
                {
                    Name = _NameError;
                }
                else
                {
                    Name = element.Name == string.Empty ? $"{GetCategoryText(element)}_{element.Id.Int64Value}" : $"{element.Name}";
                }
            }
            catch (Exception e)
            {
                ExceptionUtils.ShowExceptionMessage(e);
                return;
            }
        }
        [HandleProcessCorruptedStateExceptions]
        private string GetCategoryText(Element element)
        {
            try
            {
                var category = element.Category;
                if (null == category)
                {
                    return _unKnownCategory;
                }
                if (!element.Category.IsValidObject())
                {
                    return _unKnownCategory;
                }
                return category.Name;
            }
            catch (Exception e)
            {
                return _categoryError;
            }

        }



        public void RegisterMenu(ContextMenu contextMenu, UIElement bindableElement)
        {
            if (!CanShow) return;

            contextMenu.AddMenuItem("ScaleMatch")
                .SetHeader("缩放匹配")
                .SetCommand(_element, element =>
                {
                    if (GlodonAPI.UiDocument is null) return;
                    GlodonAPI.UiDocument.ShowElement(element.Id);
                    GlodonAPI.UiDocument.Selection.SetElementIds(new List<ElementId>(1) { element.Id });
                    GlodonAPI.UiDocument.CurrentUIView.Refresh();
                })
                .SetShortcut(bindableElement, ModifierKeys.Alt, Key.F7);
        }

        public ResolveSet Resolve(Document context, string target, ParameterInfo[] parameters)
        {
            switch (target)
            {
                case "GetTransform":
                    var transform = _element.GetTransform();
                    if (null == transform)
                    {
                        return null;
                    }
                    return ResolveSet.Append(transform);
                default:
                    return null;
            }
        }

        public ResolveSet Resolve(Document context, string target, params object[] parameterObjs)
        {
            switch (target)
            {
                case "GetGeometry":
                    var geometryOptions = parameterObjs[0] as GeometryOptions;
                    var shape = _element.GetGeometry(geometryOptions);
                    if (null == shape)
                    {
                        return null;
                    }
                    return ResolveSet.Append(shape);
                default:
                    return null;
            }
        }
    }
}
